package com.yc.fruitmarket.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.yc.fruitmarket.biz.blogBiz;
import com.yc.fruitmarket.biz.impl.blogBizImpl;
import com.yc.fruitmarket.dao.DBHelper;

@WebServlet("/blogController/*")
public class blogController extends BaseServlet {
	private DBHelper db = new DBHelper();
	private blogBiz bb = new blogBizImpl();
	
	//今日博客发表篇数
	public void sumblog(HttpServletRequest req, HttpServletResponse resp) {
		int sum = bb.sumblog();
		this.send(resp, sum);
	}
	
	//封禁判断
	public void selectbanL(HttpServletRequest req, HttpServletResponse resp) {
		String bid = req.getParameter("bid");
		int result = bb.selectbanL(bid);
		if(result == 0) {
			this.send(resp, -1);
		}else {
			result = bb.banL(bid);
			this.send(resp, result);
		}
	}
	
	//多选封禁
	public void bansL(HttpServletRequest req, HttpServletResponse resp) {
		String bids = req.getParameter("bids");
		// 使用split()方法将字符串按逗号分割成数组  
        String[] array = bids.split(",");  
        int sum = 0;
        // 遍历数组并打印每个元素  
        for (String bid : array) {  
              sum += bb.bansL(bid);
        }
        this.send(resp, sum);
	}
	
	//博客封禁
	public void banL(HttpServletRequest req, HttpServletResponse resp) {
		String bid = req.getParameter("bid");
		int result = bb.banL(bid);
		this.send(resp, result);
	}
	
	//条件查询
	public void byselectblogL(HttpServletRequest req, HttpServletResponse resp) {
		String bid = req.getParameter("bid");
		String title = req.getParameter("title");
		String uname = req.getParameter("uname");
		String start = req.getParameter("start");
		String end = req.getParameter("end");
		String btname = req.getParameter("btname");
		List<Map<String, String>> list = bb.byselectblogL(bid, title, uname, start, end, btname);
		this.send(resp, list);
	}
	
	//获取博客信息
	public void getblogL(HttpServletRequest req, HttpServletResponse resp) {
		List<Map<String, String>> list = bb.getblogL();
		for(Map<String,String> map: list) {
			map.put("value" ,map.get("title"));
		}
		this.send(resp, list);
	}
	
	public void addBlog(HttpServletRequest req, HttpServletResponse resp) {
		//获取更目录
				try {
					String webroot = this.getServletContext().getRealPath("/");
					System.out.println(webroot);
					String fileUploadPath = webroot + "../upload";
					File path = new File(fileUploadPath);
					if(!path.exists()) {
						path.mkdirs();
					}
					
					DiskFileItemFactory factory = new DiskFileItemFactory(1024*1024*10,path);
					ServletFileUpload upload = new ServletFileUpload(factory);
					upload.setFileSizeMax(1024*1024*10);
					//开始解析参数
					List<FileItem> fileItems = upload.parseRequest(req);
					//迭代器
					Iterator<FileItem> it = fileItems.iterator();
					String filePath = "";
					Map<String,String> map = new HashMap<>();
					String newFileName = "";
					while(it.hasNext()) {
						FileItem fi = it.next();
						//System.out.println(fi.getName());
						if(!fi.isFormField()) {//判断是否是文件表单域
							//说明就是图片
							InputStream is = fi.getInputStream();
							String name = fi.getName();//图片名字
							String endWith = name.substring(name.lastIndexOf("."));//	.jpg

							//格式正确写入数据
							newFileName = System.currentTimeMillis() + endWith;
							filePath = fileUploadPath + "\\" + newFileName;
							//写入
							FileOutputStream fos = new FileOutputStream(new File(filePath));
							byte[] bs = new byte[1024];
							int length = -1;
							while((length = is.read(bs)) != -1) {
								fos.write(bs,0,length);
							}
							fos.flush();
							is.close();
							fos.close();
						}else {
							//说明是普通字段	存一下数据，方便jdbc操作
							String str = new String(fi.getString().getBytes("ISO-8859-1"),"utf-8");
							map.put(fi.getFieldName(), str);
							
						}
					}
					//操作数据库
//					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//					String adate = sdf.format(new Date());
//					Map<String,String> userInfo = (Map<String, String>) req.getSession().getAttribute("userInfo");
//					String sql = "insert into article values(null,?,?,?,?,?,?,?)";
//					int result = db.doUpdate(sql, map.get("tid"),userInfo.get("usid"),map.get("title"),map.get("descript"),map.get("content"),adate,newFileName);
//					this.send(resp, result);
					String btname = map.get("btname");
					String sql = "select btid from blogtype where btname = ?";
					List<Map<String, String>> list = db.find(sql, btname);
					if(list.size() > 0) {
						int btid = Integer.parseInt(list.get(0).get("btid"));
						String insert = "insert into blog values(null,?,?,?,?,?,now(),1)";
						int result = db.doUpdate(insert, map.get("uid"),btid,newFileName,map.get("title"),map.get("text"));
						this.send(resp, result);
					}
					
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (FileUploadException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
	public void findBlogByBtid(HttpServletRequest req, HttpServletResponse resp) {
		
	}
	//分页博客
	public void getAllBlog(HttpServletRequest req, HttpServletResponse resp) {
		String btid = req.getParameter("btid");
		String blogName = req.getParameter("blogName");
		String page = req.getParameter("page");
		String pageSize = req.getParameter("pageSize");
		List<Map<String, String>> list = bb.getAllBlog(page, pageSize, blogName,btid);
		if(list.size() > 0) {
			this.send(resp, list);
		}else {
			return;
		}
	}
	//热门博客
	public void getHotBlog(HttpServletRequest req, HttpServletResponse resp) {
		List<Map<String, String>> list = bb.getHotBlog();
		if(list.size() > 0) {
			this.send(resp, list);
		}else {
			return;
		}
	}
	//具体博客
	public void findBlogD(HttpServletRequest req, HttpServletResponse resp) {
		String bid = req.getParameter("bid");
		if("".equals(bid) || bid == null) {
			return;
		}else {
			List<Map<String, String>> list = bb.findBlogD(bid);
			if(list.size() > 0) {
				this.send(resp, list.get(0));
			}else {
				return;
			}
		}
	}
	//博客评论
	public void getBlogPval(HttpServletRequest req, HttpServletResponse resp) {
		String bid = req.getParameter("bid");
		if("".equals(bid)) {
			return;
		}else {
			List<Map<String, String>> list = bb.getBlogPval(bid);
			if(list.size() > 0) {
				this.send(resp, list);
			}else {
				return;
			}
		}
	}
	//发送博客
	public void sendPval(HttpServletRequest req, HttpServletResponse resp) {
		String bid = req.getParameter("bid");
		String uid = req.getParameter("uid");
		String text = req.getParameter("text");
		if("".equals(text)||"".equals(uid)||"".equals(bid)) {
			return;
		}
		int result = bb.sendPval(uid, bid, text);
		this.send(resp, result);
	}
	//最新博客
	public void newBlog(HttpServletRequest req, HttpServletResponse resp) {
		List<Map<String, String>> list = bb.newBlog();
		this.send(resp,list);
	}
	
}
